#!/usr/bin/env python

import os
import sys
import subprocess
import re
import time
import _thread
import common

icon_fg = common.black
icon_bg = common.blue
icon_tr = "0xff"
text_fg = common.black
text_bg = common.blue
text_tr = "0xff"

icon_color = "^c" + str(icon_fg) + "^^b" + str(icon_bg) + str(icon_tr) + "^"
text_color = "^c" + str(text_fg) + "^^b" + str(text_bg) + str(text_tr) + "^"
DELAY_TIME = 1

filename = os.path.basename(__file__)
name = re.sub(r"\..*", '', filename)

vol_text = "--"
vol_icon = "ﱝ"
volumuted = ""

# 数字图标定义（0-9对应的图标）
number_icons = ["", "", "", "", "", "", "", "", "", ""]

def get_bluetooth_battery_info():
    """
    获取蓝牙设备电池信息的多种方法
    返回: 电池百分比 (整数) 或 None
    """
    try:
        # 方法1: 使用upower工具（最快最可靠）
        try:
            cmd = "upower -e 2>/dev/null | grep -i blue | head -1"
            result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            if result.returncode == 0 and result.stdout.strip():
                device = result.stdout.strip()
                cmd = f"upower -i {device} 2>/dev/null | grep -E 'percentage|Percentage' | head -1"
                result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
                if result.returncode == 0:
                    battery_match = re.search(r'(\d+)%', result.stdout)
                    if battery_match:
                        return int(battery_match.group(1))
        except:
            pass
        
        # 方法2: 检查pactl中的蓝牙设备信息（快速）
        try:
            cmd = "pactl list sinks 2>/dev/null | grep -i 'bluez\\|battery' -A 10 -B 5"
            result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            if result.returncode == 0:
                battery_match = re.search(r'(\d+)%', result.stdout)
                if battery_match:
                    return int(battery_match.group(1))
        except:
            pass
        
        return None
        
    except Exception:
        return None

def is_bluetooth_connected():
    """
    检查是否有蓝牙设备连接（快速方法）
    """
    try:
        # 方法1: 检查默认音频输出
        cmd = "pactl info 2>/dev/null | grep 'Default Sink' | grep -i bluez"
        result = subprocess.run(cmd, shell=True, timeout=1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        if result.returncode == 0:
            return True
        
        return False
        
    except:
        return False

def number_to_icons(number):
    """
    将数字转换为对应的图标序列
    例如：11 -> "", 89 -> ""
    """
    if number is None:
        return ""  # 无电池信息时返回空字符串
    
    # 确保数字在0-100范围内
    number = max(0, min(100, number))
    
    # 将数字转换为字符串，然后每位数字转换为对应的图标
    number_str = str(number)
    icon_sequence = ""
    
    for digit_char in number_str:
        if digit_char.isdigit():
            digit = int(digit_char)
            icon_sequence += number_icons[digit]
    
    return icon_sequence

def get_bluetooth_status():
    """
    获取蓝牙状态信息
    返回: (连接状态图标, 电池数字图标)
    """
    try:
        # 检查是否有蓝牙连接
        connected = is_bluetooth_connected()
        
        if not connected:
            return "󱔑", ""  # 没有连接，只有断开图标
        
        # 获取电池百分比
        battery_percent = get_bluetooth_battery_info()
        
        if battery_percent is None:
            # 有连接但无法获取电池信息
            return "󰂱", ""  # 只有连接图标
        
        # 将百分比数字转换为图标序列
        battery_icons = number_to_icons(battery_percent)
        
        return "󰂱", battery_icons  # 连接图标 + 电池数字图标
    
    except Exception:
        return "󱔑", ""  # 出错时显示断开图标

def get_vol_content():
    global vol_text
    global vol_icon
    global volumuted

    try:
        # 获取音量信息
        try:
            cmd = "pactl get-sink-mute @DEFAULT_SINK@ 2>/dev/null"
            result = subprocess.run(cmd, shell=True, timeout=1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            volumuted = "no" in result.stdout.lower()
            
            cmd = "pactl get-sink-volume @DEFAULT_SINK@ 2>/dev/null | head -1 | awk '{print $5}' | sed 's/%//'"
            result = subprocess.run(cmd, shell=True, timeout=1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            vol_text = result.stdout.strip()
            
            if not vol_text.isdigit():
                vol_text = "--"
                vol_icon = "ﱝ"
            else:
                vol = int(vol_text)
                if vol == 0: 
                    vol_icon = "婢"
                    vol_text = "00"
                else:
                    vol_icon = "墳 "
                    
        except:
            vol_text = "--"
            vol_icon = "ﱝ"
            volumuted = False
        
        # 获取蓝牙状态信息（连接图标 + 电池数字图标）
        bluetooth_icon, battery_icons = get_bluetooth_status()
        
        # 格式：音量图标+音量百分比+蓝牙连接图标+电池数字图标
        return f"{vol_icon}{vol_text}% {bluetooth_icon}{battery_icons}"
    
    except Exception:
        return f"ﱝ--% 󱔑"

# 以下函数保持不变
def update(loop=False, exec=True):
    while True:
        try:
            icon = " " + get_vol_content() + " "
            txt = "^s" + str(name) + "^" + str(icon_color) + str(icon) + str(text_color)
            common.write_to_file(txt + "\n", str(name))
            if not loop:
                if exec:
                    os.system("xsetroot -name '" + str(txt).replace("'", "'\\''") + "'")
                break
            time.sleep(DELAY_TIME)
        except Exception:
            time.sleep(DELAY_TIME)

def update_thread():
    _thread.start_new_thread(update, (False, False))

def notify(string=''):
    try:
        global vol_text
        global vol_icon
        global volumuted
        
        # 快速获取音量状态
        try:
            cmd = "pactl get-sink-mute @DEFAULT_SINK@ 2>/dev/null"
            result = subprocess.run(cmd, shell=True, timeout=1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            volumuted = "no" in result.stdout.lower()
            
            cmd = "pactl get-sink-volume @DEFAULT_SINK@ 2>/dev/null | head -1 | awk '{print $5}' | sed 's/%//'"
            result = subprocess.run(cmd, shell=True, timeout=1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
            vol_text = result.stdout.strip()
            
            if not vol_text.isdigit():
                vol_text = "0"
        except:
            vol_text = "0"
            volumuted = False

        cmd = ""
        if not volumuted:
            cmd = "notify-send -r 9527 '婢  mute'"
        else:
            cmd = f"notify-send -r 9527 -h int:value:{vol_text} -h string:hlcolor:#dddddd '{vol_icon} Volume'"
        os.system(cmd)
    except Exception:
        pass

def click(string=''):
    try:
        if string == 'L':
            notify()
        elif string == 'M':
            os.system("pactl set-sink-mute @DEFAULT_SINK@ toggle")
            notify()
        elif string == 'R':
            os.system("killall pavucontrol 2>/dev/null || pavucontrol --class floatingTerminal &")
        elif string == 'U':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ +5%")
            notify()
        elif string == 'D':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ -5%")
            notify()
    except Exception:
        pass

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == "update":
            pass
        elif sys.argv[1] == "notify":
            notify()
        else:
            update(exec=False)
            click(sys.argv[1])
            update(exec=False)
    else:
        update()
